import { useRef, useEffect } from "react";
import lodash from "lodash";

export default function useThrottle(
	fn: (...args: any[]) => void,
	delay: number
) {
	const fnRef = useRef(fn);
	const throttledFn = useRef(lodash.throttle(fn, delay));

	useEffect(() => {
		fnRef.current = fn; // 更新引用
	}, [fn]);

	useEffect(() => {
		// 创建一个新的节流函数，每次依赖变更时更新
		throttledFn.current = lodash.throttle(
			(...args) => fnRef.current(...args),
			delay
		);
	}, [delay]);

	return throttledFn.current;
}
